#include "iniconfig.h"
#include <QFile>
#include <QDir>
#include <QDebug>
#include <QApplication>

IniConfig::IniConfig(const QString &fileName, QObject *parent)
    : BaseConfig (parent)
{
    m_fileName = fileName;
}

IniConfig::~IniConfig()
{
    delete m_setting;
}

bool IniConfig::init()
{
    bool ret = true;
    QString temp;
    if (m_fileName.isEmpty())
        temp = (QApplication::applicationName() + ".ini");
    else
        temp = m_fileName;
    //Qt中使用QSettings类读写ini文件
    //如果ini文件存在则读取文件内容，否则重新创建
    if (QFile::exists(temp))
    {
        m_setting = new QSettings(temp, QSettings::IniFormat);
    }
    else
    {
        ret = false;
        qDebug() << "Create ini file : " << temp << endl;
        QFile fp;
        fp.setFileName(temp);
        fp.open(QIODevice::ReadWrite | QIODevice::Text); //包含了创建
        fp.close();
        m_setting = new QSettings(temp, QSettings::IniFormat);
    }
    return ret;
}

void IniConfig::setFileName(const QString &filename)
{
    m_fileName = filename;
}

const QString &IniConfig::getFileName() const
{
    return m_fileName;
}

bool IniConfig::get(const QString &key, QVariant &value)
{
    value = m_setting->value(key);
//    qDebug() << key << value;
    return true;
}

bool IniConfig::set(const QString &key, const QVariant &value)
{
    m_setting->setValue(key, value);
    return true;
}
